<!-- /src/views/user/shoppingmall.vue (完整替换) -->

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
// 假设你的API请求封装在 mall.js 里，代码和我们上次的一样
import { getProductList, getProductDetail, createOrder } from '@/api/mall.js';

// --- 状态定义 ---
// 你的后端接口非常清晰，所以我们的状态定义也变得超级简单！

// 搜索参数
const searchParams = ref({
  keyword: '',
  minPrice: null,
  maxPrice: null
});

// 商品列表
const productList = ref([]);
const isLoadingList = ref(false);

// 详情弹窗相关
const dialogVisible = ref(false);
const isLoadingDetail = ref(false);
// 【关键】根据你的 detail.do 接口，我们定义好 product 和 reviews
const currentProduct = ref({});
const currentReviews = ref([]);

// 下单表单
const orderForm = ref({
  quantity: 1,
  address: '宿舍楼A栋502' // 给个默认地址，方便测试
});
const isSubmittingOrder = ref(false);

// --- API 调用 ---

// 1. 获取商品列表 (对应 /products.do)
const fetchProducts = async () => {
  isLoadingList.value = true;
  try {
    // 你的接口返回 { code, data, msg }，我们直接取 data
    const res = await getProductList(searchParams.value);
    productList.value = res.data; // res.data 就是 List<Product>
    if (!productList.value || productList.value.length === 0) {
      ElMessage.info('没有找到相关商品哦~');
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败，请检查网络或联系我~');
    console.error(error);
  } finally {
    isLoadingList.value = false;
  }
};

// 2. 查看商品详情 (对应 /product/detail.do)
const showProductDetail = async (productId) => {
  dialogVisible.value = true;
  isLoadingDetail.value = true;
  try {
    const res = await getProductDetail(productId);
    // 完美对接！你的后端返回 { product: ..., reviews: ... }
    currentProduct.value = res.data.product;
    currentReviews.value = res.data.reviews;
    // 重置下单数量
    orderForm.value.quantity = 1;
  } catch (error) {
    ElMessage.error('获取商品详情失败了！');
    dialogVisible.value = false; // 失败了就关掉弹窗
    console.error(error);
  } finally {
    isLoadingDetail.value = false;
  }
};

// 3. 创建订单 (对应 /order/create.do)
const handlePlaceOrder = async () => {
  if (orderForm.value.quantity <= 0) {
    ElMessage.warning('购买数量必须大于0');
    return;
  }
  if (!orderForm.value.address.trim()) {
    ElMessage.warning('收货地址不能为空');
    return;
  }
  isSubmittingOrder.value = true;
  try {
    await createOrder({
      productId: currentProduct.value.productId,
      quantity: orderForm.value.quantity,
      address: orderForm.value.address
    });
    dialogVisible.value = false;
    ElMessage.success('下单成功！可以去“我的订单”页面支付啦！');
  } catch (error) {
    ElMessage.error(error.message || '下单失败');
    console.error(error);
  } finally {
    isSubmittingOrder.value = false;
  }
};

// 页面一加载就获取商品
onMounted(() => {
  fetchProducts();
});
</script>

<template>
  <div class="shopping-mall-container">
    <!-- 顶部搜索 -->
    <el-card shadow="never">
      <el-form :model="searchParams" inline>
        <el-form-item label="关键字">
          <el-input v-model="searchParams.keyword" placeholder="搜点什么..." clearable @keyup.enter="fetchProducts" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchProducts" :loading="isLoadingList">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-row :gutter="20" class="product-list" v-loading="isLoadingList">
      <el-col :span="6" v-for="product in productList" :key="product.productId">
        <el-card class="product-card" shadow="hover" @click="showProductDetail(product.productId)">
          <h3 class="product-name">{{ product.name }}</h3>
          <span class="product-description">{{ product.description }}</span>
          <div class="product-footer">
            <span class="product-price">¥ {{ product.price.toFixed(2) }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详情与下单弹窗 -->
    <el-dialog v-model="dialogVisible" :title="currentProduct.name || '加载中...'" width="60%">
      <div v-loading="isLoadingDetail">
        <!-- 商品信息 -->
        <el-descriptions :title="currentProduct.name" border :column="2">
          <el-descriptions-item label="价格"><span class="product-price">¥ {{ currentProduct.price?.toFixed(2) }}</span></el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentProduct.description }}</el-descriptions-item>
        </el-descriptions>

        <!-- 下单表单 -->
        <el-form :model="orderForm" label-width="80px" style="margin-top: 20px;">
          <el-form-item label="购买数量">
            <el-input-number v-model="orderForm.quantity" :min="1" :max="currentProduct.stock" />
          </el-form-item>
          <el-form-item label="收货地址">
            <el-input v-model="orderForm.address" type="textarea" />
          </el-form-item>
        </el-form>

        <!-- 评价列表 -->
        <el-divider content-position="left">用户评价</el-divider>
        <div v-if="currentReviews.length > 0">
          <div v-for="review in currentReviews" :key="review.reviewId" class="review-item">
            <span><strong>用户 {{ review.userId }}:</strong> {{ review.comment }}</span>
            <el-rate :model-value="review.rating" disabled />
          </div>
        </div>
        <el-empty v-else description="暂无评价" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">算了</el-button>
          <el-button type="danger" @click="handlePlaceOrder" :loading="isSubmittingOrder">立即下单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.product-card {
  cursor: pointer;
  margin-bottom: 20px;
}
.product-card .product-name {
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-card .product-description {
  font-size: 12px;
  color: #999;
  height: 36px;
  overflow: hidden;
}
.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
.product-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
}
.review-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 10px 0;
}
</style>